﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using SchoolProject2012.Functions;
using SchoolProject2012.Areas.Eleve.Models;


namespace SchoolProject2012.Areas.Eleve.Controllers
{
    public class ModulesController : Controller
    {
        private EleveSchoolProjectBddEntities db = new EleveSchoolProjectBddEntities();
        //
        // GET: /Eleve/Modules/
        // Affiche la liste des modules
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Index(string langue)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                string cl = Utils.getCurrentYearForClass();
                int classe = db.ELEVE.SingleOrDefault(x => x.LOGINPERS == login).ELEVECLASS.Single(c => c.CLASSE.ANNEECLASSE == cl).IDCLASS;
                var module = db.MODULE.Where(x => x.CLASSE.IDCLASSE == classe).ToList();
                return View(module);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/Details/uml
        // Affiche le détail d'un module
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Details(string langue, string id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var mods = db.MODULE.Single(x => x.LIB_MOD == id);
                ViewBag.route = id;
                return View(mods);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/open/uml?document=livre.doc
        // Ouvre un document
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Open(string langue, string id, string document)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string file = @"~/Documents/" + id + "/" + document;
                string extension = Utils.getMimeType(file);
                return File(file, extension);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/DetailsProject/erp
        // Affiche le détail d'un projet
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult DetailsProject(string langue, string id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var project = db.PROJET.Single(x => x.TITRE_PROJET == id);
                return View(project);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/DetailsGroupe
        // Affiche le détail d'un groupe
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult DetailsGroupe(string langue, int id, int idGroupe)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                var gr = db.PROJET.Single(x => x.IDPROJET == id).GROUPE.Single(x => x.IDGROUPE == idGroupe);
                ViewBag.projet = id;
                return View(gr);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/Inscription/3?idgroupe=5
        // s'inscrire à un groupe de projet
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Inscription(string langue, int id, int idgroupe)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var gr = db.PROJET.Single(x => x.IDPROJET == id).GROUPE.Single(x => x.IDGROUPE == idgroupe);
                return View(gr);
            }
            catch
            {
                return View("error");
            }
        }

        // POST: /Eleve/Modules/Inscription
        // Validation de l'inscription à un groupe de projet
        [HttpPost]
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Inscription(string langue, GROUPE groupeToSave)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                ELEVE e = db.ELEVE.Single(x => x.LOGINPERS == login);
                if (!groupeToSave.ELEVE.Contains(e))
                {
                    groupeToSave.ELEVE.Add(e);
                    db.SaveChanges();
                    return RedirectToAction("DetailsGroupe", new { groupe = groupeToSave });
                }
                return View();
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/addGroup
        // Créer un groupe de projet
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult AddGroup(string langue, int id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var projet = db.PROJET.Single(x => x.IDPROJET == id);
                return View(projet);
            }
            catch
            {
                return View("error");
            }
        }

        // POST: /Eleve/Modules/addGroup
        // Validation de l'ajout du groupe
        [HttpPost]
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult AddGroup(string langue, PROJET pr)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                db.Refresh(System.Data.Objects.RefreshMode.StoreWins, pr);
                db.SaveChanges();
                return RedirectToAction("DetailsProject", new { idProject = pr.IDPROJET });
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/Groupe
        // Affiche la vue partiel d'un groupe pour l'ajout à un projet
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public PartialViewResult Groupe(string langue, PROJET projet)
        {
            GROUPE gr = new GROUPE();
            projet.GROUPE.Add(gr);
            ViewBag.langue = langue;
            return PartialView(projet);
        }

        // GET: /Eleve/Modules/ajoutDocument/uml
        // Formulaire pour ajout d'un document
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult ajoutDocument(string langue, string id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                MODULE mod = db.MODULE.Single(x => x.LIB_MOD == id);
                ViewBag.route = RouteData.Values["id"].ToString();
                return View(mod);
            }
            catch
            {
                return View("error");
            }
        }

        // POST: /Eleve/Modules/ajoutDocument/uml
        // Validation ajout du document
        [HttpPost]
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult ajoutDocument(string langue)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                string filename = Path.GetFileName(Request.Files.Get("NOMDOCUMENT").FileName);
                filename = filename.Replace(' ', '_');
                string path = Request.PhysicalApplicationPath + "documents\\" + RouteData.Values["id"];
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                Request.Files.Get("NOMDOCUMENT").SaveAs(path + "\\" + filename);
                string id = RouteData.Values["id"].ToString();
                MODULE mod = db.MODULE.Single(x => x.LIB_MOD == id);
                DOCUMENT doc = new DOCUMENT();
                doc.NOMDOCUMENT = filename;
                doc.ID_MOD = mod.ID_MOD;
                mod.DOCUMENT.Add(doc);
                db.SaveChanges();
                ViewBag.route = id;
                return View();
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/DetailsEval/2
        // Affiche le détail d'une évaluation
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult DetailsEval(string langue, int id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var eval = db.EVALUATION.Single(x => x.IDEVAL == id);
                Session.Add("note", 0);
                return View(eval);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/Questionnaire/2
        // Affiche une question
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult Questionnaire(string langue, int id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                if (db.ELEVEEVAL.Where(x => x.IDEVAL == id).Count() != 0)
                {
                    return View("hasRep");
                }
                var eval = db.QUESTIONEVAL.Where(x => x.EVALUATION.IDEVAL == id).ToList();
                ViewBag.id = id;
                return View(eval);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/Repondre/2?quest=3
        // Affiche les réponses de la questions
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult Repondre(string langue, int id, int quest)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var hasRep = db.REPOND.Where(x => x.IDEVAL == id && x.IDQUESTEVAL == quest);
                if (hasRep.Count() != 0)
                {
                    return View("hasRep");
                }
                var reponses = db.REPONSEEVAL.Where(x => x.QUESTIONEVAL.IDQUESTEVAL == quest && x.QUESTIONEVAL.IDEVAL == id).ToList();
                return View(reponses);
            }
            catch
            {
                return View("error");
            }
        }

        // POST: /Eleve/Modules/Repondre/2?quest=3
        // Valide la réponse
        [HttpPost]
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Repondre(string langue, int id, int quest, FormCollection collect)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                int bonneRep = 0;
                foreach (var key in collect.AllKeys)
                {
                    string[] rs = collect.GetValues(key);
                    string r = rs.GetValue(0).ToString();
                    REPOND rep = new REPOND();
                    rep.LOGINPERS = login;
                    rep.IDQUESTEVAL = quest;
                    rep.IDEVAL = id;
                    int keyInt = Convert.ToInt32(key);
                    rep.IDRESPEVAL = keyInt;
                    db.REPOND.AddObject(rep);
                    db.SaveChanges();
                    var reponse = db.REPONSEEVAL.Single(x => x.IDRESPEVAL == keyInt && x.IDQUESTEVAL == quest && x.IDEVAL == id);
                    if (reponse.ESTJUSTRESPEVAL == Convert.ToBoolean(r))
                    {
                        bonneRep++;
                    }
                }
                if (bonneRep == collect.Count)
                {
                    Session["note"] = db.QUESTIONEVAL.Single(x => x.IDEVAL == id && x.IDQUESTEVAL == quest).NB_POINT_EVAL.Value + Convert.ToInt32(Session["note"]);
                }
                return RedirectToAction("Questionnaire", new { id = id });
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/Valider/2
        // Valide le formulaire
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ActionResult Valider(string langue, int id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                ELEVEEVAL e = new ELEVEEVAL();
                e.LOGINPERS = login;
                e.IDEVAL = id;
                e.NOTE = Convert.ToInt32(Session["note"]);
                db.ELEVEEVAL.AddObject(e);
                db.SaveChanges();
                return View(e);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/listEval/uml
        // Donne la liste des évaluations du module
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult listEval(string langue, string id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var evals = db.EVALUATION.Where(x => x.MODULE.LIB_MOD == id);
                return View(evals);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/listProjet/uml
        // Donne la liste des évaluations du module
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult listProjet(string langue, string id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var projet = db.PROJET.Where(x => x.MODULE.LIB_MOD == id).ToList();
                return View(projet);
            }
            catch
            {
                return View("error");
            }
        }

        // GET: /Eleve/Modules/listDocument/uml
        // Donne la liste des évaluations du module
        [Authorize(Roles = "Admin, Eleve, Delegue, BDE")]
        public ViewResult listDocument(string langue, string id)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Field.getLanguage(langue));
            ViewBag.langue = langue;
            try
            {
                string login = Session["login"].ToString();
                var docs = db.DOCUMENT.Where(x => x.MODULE.LIB_MOD == id).ToList();
                ViewBag.module = id;
                return View(docs);
            }
            catch
            {
                return View("error");
            }
        }
    }
}
